package cn.fintecher.pangolin.service.repair.web;


import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.common.utils.ZWStringUtils;
import cn.fintecher.pangolin.entity.elastic.AreaInformation;
import cn.fintecher.pangolin.service.repair.model.AreaInformationDisplayModel;
import cn.fintecher.pangolin.service.repair.model.AreaInformationModel;
import cn.fintecher.pangolin.service.repair.respository.AreaInformationRepository;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;

import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;

/**
 * Created by huyanmin on 2018/12/26.
 */
@RestController
@RequestMapping("/api/areaInformation")
@Api(value = "地区查询", description = "地区查询")
public class AreaInformationController {

    private final Logger log = LoggerFactory.getLogger(AreaInformationController.class);
    @Autowired
    private AreaInformationRepository areaInformationRepository;
    @Autowired
    ModelMapper modelMapper;

    @PostMapping(value = "/insertAreaInformation")
    @ApiOperation(notes = "新增/更新地区信息", value = "新增/更新地区信息")
    public ResponseEntity<Void> insertAreaInformation(@RequestParam String csvPath) throws IOException {
        String charset = "GBK";
        FileInputStream fileInputStream = new FileInputStream(csvPath);
        Reader reader = new InputStreamReader(fileInputStream, charset);
        Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(reader);

        Map<String, AreaInformation> resourceMap = new HashMap<>();
        for (CSVRecord record : records) {
            if (record.getRecordNumber() == 1) {
                continue;
            }
            AreaInformation areaInformation = new AreaInformation();
            areaInformation.setId(record.get(0));
            areaInformation.setPid(record.get(1));
            areaInformation.setLevel(record.get(2));
            areaInformation.setAreaName(record.get(3));
            areaInformation.setProvinceName(record.get(4));
            areaInformation.setCityName(record.get(5));
            areaInformation.setAreaName(record.get(6));
            areaInformation.setProvinceSpell(record.get(7));
            areaInformation.setCitySpell(record.get(8));
            areaInformation.setAreaFullSpell(record.get(9));
            areaInformation.setRegionalSimplicity(record.get(10));
            areaInformation.setRegionalFirstWord(record.get(11));
            areaInformation.setAreaCode("0".concat(record.get(12)));
            areaInformation.setPostCode(record.get(13));
            areaInformation.setLongitude(Double.parseDouble(record.get(14)));
            areaInformation.setLatitude(Double.parseDouble(record.get(15)));
            areaInformation.setAdministration(record.get(16));
            areaInformation.setRemark(record.get(17));
            areaInformation.setOperatorTime(ZWDateUtil.getNowDateTime());
            resourceMap.put(areaInformation.getId(), areaInformation);
        }
        if (resourceMap.size() > 0) {
            Lists.partition(new ArrayList<>(resourceMap.values()), 5000).stream().forEach(areaInformations -> areaInformationRepository.saveAll(areaInformations));
        }
        return ResponseEntity.ok().build();
    }


    @GetMapping(value = "/searchAreaInformation")
    @ApiOperation(notes = "查询所有省级", value = "查询所有省级")
    public ResponseEntity<AreaInformationModel> searchAreaInformation(@RequestParam(required = false) String pid) throws Exception {
        List<AreaInformationDisplayModel> areaList = new ArrayList<>();
        List<AreaInformation> tempList;
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if (ZWStringUtils.isEmpty(pid)) {
            tempList = IterableUtils.toList(areaInformationRepository.search(queryBuilder.must(matchPhraseQuery("level", "1"))));
        } else {
            tempList = IterableUtils.toList(areaInformationRepository.search(queryBuilder.must(matchPhraseQuery("pid", pid))));
        }
        AreaInformationModel result = new AreaInformationModel();
        if (tempList.size() > 0) {
            tempList.forEach(temp -> {
                AreaInformationDisplayModel model = new AreaInformationDisplayModel();
                model.setId(temp.getId());
                model.setPid(temp.getPid());
                if (Objects.equals(temp.getLevel(), "1")) {
                    model.setName(temp.getProvinceName());
                } else if (Objects.equals(temp.getLevel(), "2")) {
                    model.setName(temp.getCityName());
                } else {
                    model.setName(temp.getAreaName());
                }
                model.setAreaCode(temp.getAreaCode());
                areaList.add(model);
            });
            result.setAreaList(areaList);
        }
        return ResponseEntity.ok(result);
    }

}
